home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / BitTorrent / parseargs.py < prev    next >
Encoding:
Python Source  |  2007-11-12  |  3.5 KB  |  115 lines

  1. # Written by Bill Bumgarner and Bram Cohen
  2. # see LICENSE.txt for license information
  3.  
  4. from types import *
  5. from cStringIO import StringIO
  6.  
  7. def formatDefinitions(options, COLS):
  8.     s = StringIO()
  9.     indent = " " * 10
  10.     width = COLS - 11
  11.  
  12.     if width < 15:
  13.         width = COLS - 2
  14.         indent = " "
  15.  
  16.     for (longname, default, doc) in options:
  17.         s.write('--' + longname + ' <arg>\n')
  18.         if default is not None:
  19.             doc += ' (defaults to ' + repr(default) + ')'
  20.         i = 0
  21.         for word in doc.split():
  22.             if i == 0:
  23.                 s.write(indent + word)
  24.                 i = len(word)
  25.             elif i + len(word) >= width:
  26.                 s.write('\n' + indent + word)
  27.                 i = len(word)
  28.             else:
  29.                 s.write(' ' + word)
  30.                 i += len(word) + 1
  31.         s.write('\n\n')
  32.     return s.getvalue()
  33.  
  34. def usage(str):
  35.     raise ValueError(str)
  36.  
  37. def parseargs(argv, options, minargs = None, maxargs = None):
  38.     config = {}
  39.     longkeyed = {}
  40.     for option in options:
  41.         longname, default, doc = option
  42.         longkeyed[longname] = option
  43.         config[longname] = default
  44.     options = []
  45.     args = []
  46.     pos = 0
  47.     while pos < len(argv):
  48.         if argv[pos][:2] != '--':
  49.             args.append(argv[pos])
  50.             pos += 1
  51.         else:
  52.             if pos == len(argv) - 1:
  53.                 usage('parameter passed in at end with no value')
  54.             key, value = argv[pos][2:], argv[pos+1]
  55.             pos += 2
  56.             if not longkeyed.has_key(key):
  57.                 usage('unknown key --' + key)
  58.             longname, default, doc = longkeyed[key]
  59.             try:
  60.                 t = type(config[longname])
  61.                 if t is NoneType or t is StringType:
  62.                     config[longname] = value
  63.                 elif t in (IntType, LongType):
  64.                     config[longname] = long(value)
  65.                 elif t is FloatType:
  66.                     config[longname] = float(value)
  67.                 else:
  68.                     assert 0
  69.             except ValueError, e:
  70.                 usage('wrong format of --%s - %s' % (key, str(e)))
  71.     for key, value in config.items():
  72.         if value is None:
  73.             usage("Option --%s is required." % key)
  74.     if minargs is not None and len(args) < minargs:
  75.         usage("Must supply at least %d args." % minargs)
  76.     if maxargs is not None and len(args) > maxargs:
  77.         usage("Too many args - %d max." % maxargs)
  78.     return (config, args)
  79.  
  80. def test_parseargs():
  81.     assert parseargs(('d', '--a', 'pq', 'e', '--b', '3', '--c', '4.5', 'f'), (('a', 'x', ''), ('b', 1, ''), ('c', 2.3, ''))) == ({'a': 'pq', 'b': 3, 'c': 4.5}, ['d', 'e', 'f'])
  82.     assert parseargs([], [('a', 'x', '')]) == ({'a': 'x'}, [])
  83.     assert parseargs(['--a', 'x', '--a', 'y'], [('a', '', '')]) == ({'a': 'y'}, [])
  84.     try:
  85.         parseargs([], [('a', 'x', '')])
  86.     except ValueError:
  87.         pass
  88.     try:
  89.         parseargs(['--a', 'x'], [])
  90.     except ValueError:
  91.         pass
  92.     try:
  93.         parseargs(['--a'], [('a', 'x', '')])
  94.     except ValueError:
  95.         pass
  96.     try:
  97.         parseargs([], [], 1, 2)
  98.     except ValueError:
  99.         pass
  100.     assert parseargs(['x'], [], 1, 2) == ({}, ['x'])
  101.     assert parseargs(['x', 'y'], [], 1, 2) == ({}, ['x', 'y'])
  102.     try:
  103.         parseargs(['x', 'y', 'z'], [], 1, 2)
  104.     except ValueError:
  105.         pass
  106.     try:
  107.         parseargs(['--a', '2.0'], [('a', 3, '')])
  108.     except ValueError:
  109.         pass
  110.     try:
  111.         parseargs(['--a', 'z'], [('a', 2.1, '')])
  112.     except ValueError:
  113.         pass
  114.  
  115.